package serializer;

import common.RPCRequest;
import common.RPCResponse;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.AllArgsConstructor;

@AllArgsConstructor
public class MyEncode extends MessageToByteEncoder {
    private Serializer serializer;
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object o, ByteBuf byteBuf) throws Exception {
        if(o instanceof RPCRequest){
            byteBuf.writeShort(MessageType.REQUEST.getCode());
        }else if(o instanceof RPCResponse){
            byteBuf.writeShort(MessageType.RESPONSE.getCode());
        }

        byteBuf.writeShort(serializer.getType());
        byte[] bytes = serializer.serialize(o);
        byteBuf.writeInt(bytes.length);
        byteBuf.writeBytes(bytes);
    }
}
